package cc.yiueil.interceptor;

import cc.yiueil.vo.ResultVo;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class CustomWebBlockInterceptor implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        ResultVo failResult = ResultVo.fail(500, "错误: Blocked by Sentinel (flow limiting)");
        out.print(objectMapper.writeValueAsString(failResult));
        out.flush();
        out.close();
    }
}
